package com.gamex.findit.controller.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gamex.findit.ResultCode;
import com.gamex.findit.internal.DefaultConfig;
import com.gamex.findit.model.ADImage;
import com.gamex.findit.model.Image;
import com.gamex.findit.model.ImageCut;
import com.gamex.findit.service.ADImageService;
import com.gamex.findit.service.ImageService;
import com.gamex.findit.util.CommonUtil;

@Controller
public class ImageListController {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageListController.class);
	
	@Autowired ImageService imageService;
	@Autowired ADImageService adImageService;
	@Autowired DefaultConfig config;
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param image
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/newImageList.*")
	public ResponseEntity<String> newImageList( HttpSession session
			  			   , HttpServletRequest request
						   , HttpServletResponse response
						   , ModelMap model
						   , @ModelAttribute Image image) throws Exception{
		
	HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=utf-8");
	ModelMap body = new ModelMap();
	List<Image>	result = null;
	List<Image> imgList = new ArrayList<Image>();
	
	try {
		
		result = imageService.getImage(image);
		for (int i = 0; i < result.size(); i++) {
			List<ImageCut> cuts = imageService.selectImageCutList(result.get(i).getImgId());
			
			ADImage adImage = new ADImage();
			adImage.setImgId(result.get(i).getImgId());
			ADImage ad = adImageService.getADView(adImage);
			result.get(i).setImageCut(cuts);
			result.get(i).setAdImage(ad);
			imgList.add(result.get(i));
		}
		
		body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
	} catch (Exception e) {
		body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
	}
	
	body.addAttribute("list", imgList);
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	

}
